package com.heeexy.example.service;

import com.alibaba.fastjson.JSONObject;
import com.heeexy.example.dto.session.SessionUserInfo;
import com.heeexy.example.service.TokenService;
import com.heeexy.example.dao.IpMacDao;
import com.heeexy.example.util.CommonUtil;
import com.heeexy.example.util.constants.ErrorEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;


/**
 * @author: heeexy
 * @date: 2017/10/24 16:07
 */
@Service
@Slf4j
public class IpMacService {
    private int adminId = 10003;

    @Autowired
    private IpMacDao ipMacDao;

    @Autowired
    TokenService tokenService;

    /**
     * 新增IP-MAC
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject addIpMac(JSONObject jsonObject) {
        SessionUserInfo userInfo = tokenService.getUserInfo();
        if (CommonUtil.checkIp(jsonObject.getString("ip"))) {
            return CommonUtil.errorJson(ErrorEnum.E_90002);
        }

        log.debug("add mac userid={}", userInfo.getUserId());
        if(userInfo.getUserId()== adminId){ // 管理员
            ipMacDao.addIpMac(jsonObject);
        }else{ //普通用户
            String mac = userInfo.getMac();
            log.debug("add mac={}", mac);
            jsonObject.put("mac",userInfo.getMac());
            ipMacDao.addIpMac(jsonObject);
        }

        try{
            String cmds = String.format("/usr/bin/python /home/hzz/ip-mac-bind.py cx-12f %s %s",jsonObject.getString("ip"),jsonObject.getString("mac"));
            log.debug("add mac cmds={}", cmds);
            Process pcs = Runtime.getRuntime().exec(cmds);
            pcs.waitFor();
            BufferedReader in = new BufferedReader(new InputStreamReader(pcs.getInputStream(),"GB2312"));
            log.debug("add mac readling over");
            String line = null;
            while ((line = in.readLine()) != null) {
                log.info(line);
            }
            in.close();
        }catch (IOException e) {
            log.debug("add mac readling IOException");
            log.error(e.getMessage());
            e.printStackTrace();
        }catch (InterruptedException e) {
            log.debug("add mac readling Interruptedexception");
            log.error(e.getMessage());
            e.printStackTrace();
        }

        return CommonUtil.successJson();
    }

    /**
     * IP-MAC列表
     */
    public JSONObject listIpMac(JSONObject jsonObject) {
        SessionUserInfo userInfo = tokenService.getUserInfo();
        if(userInfo.getUserId()== adminId){ // 管理员
            CommonUtil.fillPageParam(jsonObject);
            int count = ipMacDao.countIpMac(jsonObject);
            List<JSONObject> list = ipMacDao.listIpMac(jsonObject);
            return CommonUtil.successPage(jsonObject, list, count);
        }else{
            CommonUtil.fillPageParam(jsonObject);
            jsonObject.put("userId",userInfo.getUserId());
            List<JSONObject> list = ipMacDao.listIpMacbyUserId(jsonObject);
            return CommonUtil.successPage(jsonObject, list, list.size());
        }
    }

    /**
     * 更新IP-MAC
     */
    @Transactional(rollbackFor = Exception.class)
    public JSONObject updateIpMac(JSONObject jsonObject) {
        if (CommonUtil.checkIp(jsonObject.getString("ip"))) {
            return CommonUtil.errorJson(ErrorEnum.E_90002);
        }
        ipMacDao.updateIpMac(jsonObject);
        SessionUserInfo userInfo = tokenService.getUserInfo();

        try {
            String cmds = String.format("/usr/bin/python /home/hzz/ip-mac-bind.py cx-12f %s %s",jsonObject.getString("ip"),userInfo.getMac());
            //String cmds = String.format("/usr/bin/python3.8 /home/hzz/test.py");
            log.debug("update mac cmds={}", cmds);
            Process pcs = Runtime.getRuntime().exec(cmds);
            BufferedReader in = new BufferedReader(new InputStreamReader(pcs.getInputStream()));
            String line = null;
            log.info("test");
            while ((line = in.readLine()) != null) {
                log.info("test");
                System.out.println(line);
                log.info(line);
            }
            in.close();
            pcs.waitFor();
        }catch (IOException e) {
            e.printStackTrace();
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
        return CommonUtil.successJson();
    }
}
